package com.acme.bankapp.domain.bank.account;

import com.acme.bankapp.service.bank.exception.NotEnoughFundsException;
import com.acme.bankapp.service.bank.exception.OverDraftLimitExceededException;

public class CheckingAccount extends AbstractAccount {
	private final static String MESSAGE_ERROR_OVERDRAFT = "Overdraft less zero";
	
	
	private double overdraft;
	
	public CheckingAccount(double balance, double overdraft) throws IllegalArgumentException {
		super(balance);
		if (overdraft < 0) {
			throw new IllegalArgumentException(MESSAGE_ERROR_OVERDRAFT);
		}
		this.overdraft = overdraft;
	}
	
	@Override
	public void withdraw(double x) throws IllegalArgumentException, OverDraftLimitExceededException {
		if (x < 0) {
			throw new IllegalArgumentException(super.MESSAGE_ERROR_ARGUMENT);
		}
		
		try {
			super.withdraw(x);
		} catch (NotEnoughFundsException exception) {
			if (balance + overdraft < x)
				new OverDraftLimitExceededException(balance, overdraft);
			super.balance -= (x - overdraft);
		}
		
		assert balance + overdraft >= 0 : "Balance and Overdraft less diff";
	}
	
	@Override
	public double maximumAmountToWithdraw() {
		return super.maximumAmountToWithdraw() + overdraft;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		long temp;
		temp = Double.doubleToLongBits(overdraft);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		CheckingAccount other = (CheckingAccount) obj;
		if (overdraft != other.overdraft)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return super.toString() + " [" + overdraft + "]";
	}
}
